<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js canvas - combo camera - orthographic + perspective</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
			body {
				font-family: Monospace;
				background-color: #f0f0f0;
				margin: 0px;
				overflow: hidden;
				color: purple;
			}
.explain1{
	margin-top:10px;
	text-align:left;
	padding-left:30px;
	font-size:30px;
	position:absolute;
	right:50px;
	font-weight: bolder;
}
.explain2{
	margin-top:10px;
	text-align:left;
	padding-left:30px;
	font-size:30px;
	position:absolute;
	right:50px;
	top:50px;
	font-weight: bolder;
}
.explain3{
	margin-top:10px;
	text-align:left;
	padding-left:30px;
	font-size:30px;
	position:absolute;
	right:50px;
	top:100px;
	font-weight: bolder;
}
			a {
				color: red;
			}

			button{
			padding:12px;
			font-size:26px;
			margin:30px;
			cursor:pointer;
			clear:both;
			background-color:#0b2e13;
            border: 2px solid white;
            opacity: 0.75;
            color: #fff;
			border-radius: 5px;
            width:160px;
            transition: all 0.3s;
				position:absolute;
				right:50px;
				top:150px;
		}



		</style>
	</head>
	<body>

		<script src="/static/three/build/three.js"></script>
<script src="/static/three/js/controls/OrbitControls.js"></script>
		<script src="/static/three/js/cameras/CombinedCamera.js"></script>

		<script src="/static/three/js/renderers/Projector.js"></script>
		<script src="/static/three/js/renderers/CanvasRenderer.js"></script>

		<script src="/static/three/js/libs/stats.min.js"></script>
		<script src="/static/js/html2canvas.min.js"></script>
<!--		<script src="/static/js/canvas2image.js"></script>-->
		 <script src="http://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>

		<div style="position: absolute; top: 10px; width: 100%; text-align: right; ">
				 <div class="explain1">货币值：{{data.plan[1]}}</div>

				<div class="explain2">光照时长：{{data.plan[2]}} h</div>
                    <div class="explain3">建筑密度：{{data.plan[3]}}</div>
			<button id = "save">保存本方案</button>
			<a id="tttt"></a>
<!--			视角: <a href="#" onclick="setOrthographic();return false;"> Orthographic</a> |-->
<!--			-->
<!--			缩放: <a href="#" onclick="setLens(8);return false;">远1</a> |-->
<!--				<a href="#" onclick="setLens(12);return false;">远2</a> |-->
<!--				<a href="#" onclick="setLens(16);return false;">近1</a> |-->
<!--				<a href="#" onclick="setLens(25);return false;">近2</a> |-->
<!--		-->
<!--			-->
<!--			-->
<!--	-->
<!--				<a href="#" onclick="lookAtScene=true;return false;">Look at Scene</a>-->
<!--				<br/>-->
<!--				-->
				
				
			<div id="fov"></div>
		</div>



		<script>


$("#save").on("click", function(event) {
	event.preventDefault();
	html2canvas(document.body, {
		allowTaint: true,
		taintTest: false,
		onrendered: function(canvas) {
			canvas.id = "mycanvas";
			//生成base64图片数据
			var dataUrl = canvas.toDataURL();
			var newImg = document.createElement("img");
			newImg.src = dataUrl;
			document.body.appendChild(newImg);
			var pos = dataUrl.indexOf("4") + 2;
			dataUrl = dataUrl.substring(pos, dataUrl.length - pos);//去掉Base64:开头的标识字符
			var dataUrl = canvas.toDataURL();
			 var triggerDownload = $("#tttt").attr("href", dataUrl).attr("download", "plan.png");
  		  triggerDownload[0].click();



    //             var newImg = document.createElement("img");
    //             //newImg.style = "display:none;";    //如果要导出，这儿可以隐藏，然后用canvas2image搞定
    //             newImg.src =  dataUrl;
    //


			// $.ajax({
			// 	type: "POST",
			// 		url:"",
			// 		async: false,
			// 		data: { 'base64StrImgData': dataUrl},
			// 		dataType: "text",
			// 		beforeSend: function (request) {
			// 	},
			// 	success: function (data) {
			//
			// 	}
			// });
		}
	});
});




			pid = {{data.pid}};
			plan = {{data.plan}};
			var builds = {{data.plan[4]}};
			var arr = {{data.arr}};
			var container, stats,controls;
			var camera, scene, renderer;
			var lookAtScene = true;

			init();
			animate();

			function setOrthographic() {

				camera.toOrthographic();

			

			}

			function setPerspective() {

				camera.toPerspective();

				document.getElementById('fov').innerHTML = 'Perspective mode' ;

			}

			function init() {
				
				container = document.createElement( 'div' );
				document.body.appendChild( container );

				//camera = new THREE.CombinedCamera( window.innerWidth / 2, window.innerHeight / 2, 70, 1, 1000, -500, 1000 );
					//CombinedCamera(width,height,fov(相机角度),near（相机的近平面视角）,far（远平面视角）,orthoNera（近平面视图）,orthoFar)
				camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 1000 );
				

				
				//camera = new THREE.PerspectiveCamera(50,window.innerWidth/window.innerHeight,1,1000,1)
				//camera.lookAt(500,0,500);
				camera.position.x = -150;
				camera.position.y = 400;
				camera.position.z = 500;
				scene = new THREE.Scene();
				
				scene.add( camera );
				
				// Grid网格; 方格

				var size = 500, step = 100;

				var geometry = new THREE.Geometry();

				for ( var i = -size; i <= size; i += step ) {

					geometry.vertices.push( new THREE.Vector3( - size, 0, i ) );
					geometry.vertices.push( new THREE.Vector3(   size, 0, i ) );

					geometry.vertices.push( new THREE.Vector3( i, 0, - size ) );
					geometry.vertices.push( new THREE.Vector3( i, 0,   size ) );

				}

				var material = new THREE.LineBasicMaterial( { color:0xf00ff, opacity: 0.03 } );

				var line = new THREE.LineSegments( geometry, material );
				scene.add( line );

				// Cubes
				//首先把地面给for循环出来
				// for(var i=0;i<500;i++)
				// {
				// 	for(var j=0;j<500;j++)
				// 	{
				// 		if(arr[i][j]==9)
				// 		{
				// 			//填补区域
				// 			var geometry = new THREE.BoxGeometry(1 , 5, 1);//长高宽
				// 			var material = new THREE.MeshLambertMaterial( { color:0xff0000, overdraw: 0.5 } );
				// 			var cube = new THREE.Mesh( geometry, material );
				// 			cube.position.x = 2*j-500;
				// 			cube.position.y = 0;
				// 			cube.position.z = 2*i-500;
				// 			scene.add(cube);
				// 		}
				// 	}
				// }


				for (var i=0;i<builds.length;i++)
				{

					var cx = builds[i][0]-500;//左上角x
					var cy = builds[i][1]-500;//左上角y

					var long =  builds[i][2];
					var high = builds[i][4];
					var wide =  builds[i][3];
					bb(cx,cy,high,long,wide,10,0x000000,'#fce77e');

					// var geometry = new THREE.BoxGeometry( long, high, wide );//长高宽
					// var material = new THREE.MeshLambertMaterial( { color:0x969696 , overdraw: 0.5 } );
					// var cube = new THREE.Mesh( geometry, material );
					// cube.position.x = cx+long/2;
					// cube.position.y = high/2;
					// cube.position.z = cy+wide/2;
					// scene.add(cube);
				}




				// var plane = new THREE.PlaneGeometry(1000,1000)
				// var texture = new THREE.TextureLoader().load("/static/img/map.jpg");
				// var material = new THREE.MeshPhongMaterial({
				// 	 map:texture,
				// 	// 矩形平面网格模型默认单面显示，可以设置side属性值为THREE.DoubleSide双面显示
				// 	side: THREE.DoubleSide,
				// });
				//
				// var mesh = new THREE.Mesh(plane, material);
				// mesh.rotation.set(-0.5 * Math.PI, 0, 0);
				//
				// scene.add(mesh);


				// for ( var i = 0; i < 40; i ++ ) {

				// 	var cube = new THREE.Mesh( geometry, material );

				// 	cube.scale.y = Math.floor( Math.random() * 2 + 1 );

				// 	cube.position.x = Math.floor( ( Math.random() * 1000 - 500 ) / 50 ) * 50;
				// 	cube.position.y = ( cube.scale.y * 50 ) / 2;
				// 	cube.position.z = Math.floor( ( Math.random() * 1000 - 500 ) / 50 ) * 50;

				// 	scene.add(cube);

				// }

				// Lights

				var ambientLight = new THREE.AmbientLight( 100 );
				scene.add( ambientLight );

				var directionalLight = new THREE.DirectionalLight(  0xffffff );
				directionalLight.position.x =600 - 0.5;
				directionalLight.position.y =1000 - 0.5;
				directionalLight.position.z = 1000 - 0.5;
				directionalLight.position.normalize();
				scene.add( directionalLight );

				var directionalLight = new THREE.DirectionalLight( 0xffffff );
				directionalLight.position.x = 4000 - 0.5;
				directionalLight.position.y = 5000 - 0.5;
				directionalLight.position.z = 8000 - 0.5;
				directionalLight.position.normalize();
				scene.add( directionalLight );

				renderer = new THREE.CanvasRenderer();
				renderer.setClearColor( 0xf0f0f0 );
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				container.appendChild( renderer.domElement );

				stats = new Stats();
				container.appendChild( stats.dom );

			/*	window.addEventListener( 'resize', onWindowResize, false );

				function onWindowResize(){

					camera.setSize( window.innerWidth, window.innerHeight );
					camera.updateProjectionMatrix();

					renderer.setSize( window.innerWidth, window.innerHeight );

				}*/
				
				
				var controls = new THREE.OrbitControls(camera);
				controls.maxPolarAngle=1.2;
				controls.minPolarAngle=0;
				controls.enableDamping = true;  
				//是否可以缩放  
				controls.enableZoom = true;  
				//是否自动旋转  
				controls.autoRotate = true;  
				//设置相机距离原点的最远距离  
				controls.minDistance = 200;  
				//设置相机距离原点的最远距离  
				controls.maxDistance = 600;  
				//是否开启右键拖拽  
				controls.enablePan = true; 
				
				controls.dampingFactor = 0.7;
				
				
				
				 var axes = new THREE.AxisHelper(500);
				camera.lookAt(new THREE.Vector3(0,0,0));
				//坐标系
				//scene.add(axes);

			}

			//

			function animate() {

				requestAnimationFrame( animate );

				stats.begin();
				render();
				stats.end();

			}

			function render() {

				var timer = Date.now() * 0.0001;
				//旋转代码
				//camera.position.x = Math.cos( timer ) * 200;
				//camera.position.z = Math.sin( timer ) * 200;
				//if ( lookAtScene ) camera.lookAt( scene.position );
			
				renderer.render( scene, camera );

			}



function SimpleCube(x, y, z, num, l,w,h,color1,color2) {
    //魔方左上角坐标
    var leftUpX = x - num / 2 * l;
    var leftUpY = y + num / 2 * h;
    var leftUpZ = z + num / 2 * w;
    //根据颜色生成材质
    var materialArr = [];
    for (var i = 0; i < 6; i++) {
        var texture = new THREE.Texture(faces2(color1,color2));
        texture.needsUpdate = true;
		var material1 = new THREE.MeshLambertMaterial( { map:texture ,side: THREE.FrontSide} );
        materialArr.push(material1);
    }
    var cubes = [];
    for (var i = 0; i < num; i++) {
        for (var j = 0; j < num * num; j++) {
            var cubegeo = new THREE.BoxGeometry(l, h, w);
            var cube = new THREE.Mesh(cubegeo, material1);
            //依次计算各个小方块中心点坐标
            cube.position.x = (leftUpX + l / 2) + (j % num) * l;
            cube.position.y = (leftUpY - h / 2) - parseInt(j / num) * h;
            cube.position.z = (leftUpZ - w / 2) - i * w;
            cubes.push(cube)
        }
    }
    return cubes;
}
//生成canvas素材
function faces(rgbaColor) {
    var canvas = document.createElement('canvas');
    canvas.width = 256;
    canvas.height = 256;
    var context = canvas.getContext('2d');
    if (context) {
        //画一个宽高都是256的黑色正方形
        context.fillStyle = '#fce77e';
        context.fillRect(0, 0, 256, 256);
        //在内部用某颜色的16px宽的线再画一个宽高为224的圆角正方形并用改颜色填充
       	var len = 50;

        context.rect(len,len,256-2*len,256-2*len);
        context.lineJoin = 'round';
        context.lineWidth = 16;
        context.fillStyle = rgbaColor;
        context.strokeStyle = rgbaColor;
        context.stroke();
        context.fill();
    } else {
        alert('您的浏览器不支持Canvas无法预览.\n');
    }
    return canvas;
}



function faces2(color1,color2) {
    var canvas = document.createElement('canvas');
    canvas.width = 240;
    canvas.height = 120;
    var context = canvas.getContext('2d');
    if (context) {
        //画一个宽高都是256的黑色正方形
        context.fillStyle = color1;
        context.fillRect(0, 0, 240, 120);
        //在内部用某颜色的16px宽的线再画一个宽高为224的圆角正方形并用改颜色填充
       	var len = 50;
		context.rect(40,30,15,40);
		context.rect(110,30,15,40);
		context.rect(180,30,15,40);
        //context.rect(len,len,256-2*len,256-2*len);
        context.lineJoin = 'round';
        context.lineWidth = 16;
        context.fillStyle =color2;
        context.strokeStyle =color2;
        context.stroke();
        context.fill();
    } else {
        alert('您的浏览器不支持Canvas无法预览.\n');
    }
    return canvas;
}


//创建展示场景所需的各种元素
var cubes
function initObject(x,y,z,len,width,height,color1,color2) {
    //生成魔方小正方体
    cubes = SimpleCube(x,y,z,1,len,width,height,color1,color2);
    for(var i=0;i<cubes.length;i++){
        var item = cubes[i];
        scene.add(cubes[i]);//并依次加入到场景中
    }
}
//我需要写一个方法
			// 参数：左上x，左上y，楼层数，楼长，楼宽，每层楼楼高，颜色
			function bb(x,y,floor,l,w,h,color1,color2) {
				for (var i = 1; i <= floor; i++) {
					var top = i * h;//每层楼的左上角高度
					initObject(x, top, y, l, w, h, color1, color2);
				}
				var geometry = new THREE.BoxGeometry(l, h / 3, w);//长高宽
				var material = new THREE.MeshLambertMaterial({color: color1, overdraw: 0.5});
				var c = new THREE.Mesh(geometry, material);
				c.position.x = x;
				c.position.y =top+h*2/3;
				c.position.z = y;
				scene.add(c);



			}
		</script>

	</body>
</html>
